package admin

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

type AdminContext struct {
	*gin.Context
	Data map[string]interface{}
}

func (c *AdminContext) Set(k string, v interface{}) {
	c.Data[k] = v
}

func (c *AdminContext) Get(k string) (interface{}, bool) {
	v, ok := c.Data[k]
	return v, ok
}

func (c *AdminContext) CurrentUser() *LoginInfo {
	info := new(LoginInfo)
	if id, ok := c.Context.Get("userId"); ok {
		info.ID = uint(id.(float64))
	}
	if id, ok := c.Context.Get("roleId"); ok {
		info.RoleID = uint(id.(float64))
	}
	if username, ok := c.Context.Get("username"); ok {
		info.Username = username.(string)
	}
	return info
}

func (c *AdminContext) Sucess(data interface{}, msg string) {
	c.JSON(200, gin.H{
		"status": 0,
		"data":   data,
		"msg":    msg,
	})
}

func (c *AdminContext) Fail(msg string) {
	c.JSON(200, gin.H{
		"status": 1,
		"data":   nil,
		"msg":    msg,
	})
}

type HandlerFunc func(*AdminContext)

func Handler(h HandlerFunc) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		c := new(AdminContext)
		c.Context = ctx
		// todo some
		h(c)
	}
}

func JwtAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if token, err := c.Cookie("token"); err == nil {
			c.Request.Header.Set("Authorization", "Bearer "+token)
		}
		token, err := TokenValid(c)
		if err != nil {
			// 没有登录请求试图跳转登录界面
			if strings.Contains(c.GetHeader("Accept"), "application/json") {
				c.String(http.StatusUnauthorized, err.Error())
				c.Abort()
			} else {
				c.Redirect(http.StatusFound, "/login")
			}
			return
		}
		claims := token.Claims.(jwt.MapClaims)
		c.Set("userId", claims["userId"])
		c.Set("username", claims["username"])
		c.Set("roleId", claims["roleId"])
		c.Next()
	}
}
